<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">
<meta name="baidu-site-verification" content="code-Vc9hmj7JE9" />
<meta name="google-site-verification" content="tMVEtTlHbEdIEga44DZi47Yu8Pl2shFKVZcqz6rfSW0" />
<script>
    (function () {
        if ('') {
            if (prompt('请输入文章密码') !== '') {
                alert('密码错误！');
                if (history.length === 1) {
                    location.replace("https://kun-bin.github.io/");
                } else {
                    history.back();
                }
            }
        }
    })();
</script>








<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />
<link rel="stylesheet" type="text/css" href="/css/matery.css">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="python," />










<meta name="description" content="这一课是numpy库。 import numpy as py">
<meta property="og:type" content="article">
<meta property="og:title" content="python课程记录-10">
<meta property="og:url" content="https://likun1208.github.io/2020/04/29/python%E8%AF%BE%E7%A8%8B%E8%AE%B0%E5%BD%95-10/index.html">
<meta property="og:site_name" content="左边">
<meta property="og:description" content="这一课是numpy库。 import numpy as py">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-04-29T02:32:48.000Z">
<meta property="article:modified_time" content="2020-12-21T06:31:24.690Z">
<meta property="article:author" content="Kun Li">
<meta property="article:tag" content="python">
<meta name="twitter:card" content="summary">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"left","display":"always","offset":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://likun1208.github.io/2020/04/29/python课程记录-10/"/>





  <title>python课程记录-10 | 左边</title>
  








<meta name="generator" content="Hexo 4.2.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">左边</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            Tags
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            Categories
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            Archives
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            Search
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="Searching..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>
	<script type="text/javascript" src="/js/echarts.min.js"></script>
    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://likun1208.github.io/2020/04/29/python%E8%AF%BE%E7%A8%8B%E8%AE%B0%E5%BD%95-10/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Kun Li">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/header.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="左边">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">python课程记录-10</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2020-04-29T10:32:48+08:00">
                2020-04-29
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E8%AF%BE%E7%A8%8B%E7%AC%94%E8%AE%B0/" itemprop="url" rel="index">
                    <span itemprop="name">课程笔记</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>这一课是numpy库。</p>
<p><code>import numpy as py</code></p>
<a id="more"></a>
<h2 id="创建数组基本方法："><a href="#创建数组基本方法：" class="headerlink" title="创建数组基本方法："></a>创建数组基本方法：</h2><ol>
<li><p><code>array()</code></p>
<p>python对象转换为数组</p>
</li>
<li><p><code>empty()</code></p>
<p>分配指定大小数组，不初始化</p>
</li>
<li><p><code>zeros()</code>,<code>ones()</code></p>
<p>建立全为0或1的数组</p>
</li>
<li><p><code>eye()</code>,<code>diag()</code></p>
<p>建立对角矩阵</p>
</li>
<li><p><code>arange()</code></p>
<p>初值、终值、步长建立一维数组</p>
</li>
<li><p><code>linspace()</code></p>
<p>初值、终值、元素个数建立一维数组</p>
</li>
<li><p><code>logspace</code></p>
<p>初值、终值、元素个数建立等比数列</p>
</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line">a &#x3D; np.array((1,2,3,4))</span><br><span class="line">array([1, 2, 3, 4])</span><br><span class="line">b &#x3D; np.array([[1,2,3,4],[4,5,6,7],[7,8,9,10]])</span><br><span class="line">array([[ 1,  2,  3,  4],</span><br><span class="line">       [ 4,  5,  6,  7],</span><br><span class="line">       [ 7,  8,  9, 10]])		</span><br><span class="line">c &#x3D; a.tolist()</span><br><span class="line">[1,2,3,4]</span><br><span class="line">d &#x3D; np.empty((2,2))	#这里数组维数必须是是元组</span><br><span class="line">array([[9.90263869e+067, 9.38159477e-312],</span><br><span class="line">       [0.00000000e+000, 9.38983138e-312]])       </span><br><span class="line">e &#x3D; np.ones((2,2))</span><br><span class="line">array([[1., 1.],</span><br><span class="line">       [1., 1.]])       </span><br><span class="line">f &#x3D; np.diag((2,3,4))</span><br><span class="line">array([[2, 0, 0],</span><br><span class="line">       [0, 3, 0],</span><br><span class="line">       [0, 0, 4]])       </span><br><span class="line">g &#x3D; np.eye(3)</span><br><span class="line">array([[1., 0., 0.],</span><br><span class="line">       [0., 1., 0.],</span><br><span class="line">       [0., 0., 1.]])       </span><br><span class="line">h &#x3D; np.eye(2,3)</span><br><span class="line">array([[1., 0., 0.],</span><br><span class="line">       [0., 1., 0.]])</span><br><span class="line">i &#x3D; np.arange(5,10,1)</span><br><span class="line">array([5, 6, 7, 8, 9])</span><br><span class="line">j &#x3D; np.linspace(5,10,4)</span><br><span class="line">array([ 5.        ,  6.66666667,  8.33333333, 10.        ])</span><br><span class="line">k &#x3D; np.logspace(0,1,5)</span><br><span class="line">array([ 1.        ,  1.77827941,  3.16227766,  5.62341325, 10.        ])</span><br></pre></td></tr></table></figure>
<h2 id="数组的基本属性"><a href="#数组的基本属性" class="headerlink" title="数组的基本属性"></a>数组的基本属性</h2><ol>
<li><code>ndim</code>：数组的维度，也就是有几行</li>
<li><code>shape</code>：数组每维大小，元组形式</li>
<li><code>size</code>：数组里一共多少个元素</li>
<li><code>dtype</code>：数组数据类型</li>
<li><code>itemsize</code>：元素字节数</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">d1 = np.array([<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>])</span><br><span class="line">d2 = np.array([[<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>],[<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>]])</span><br><span class="line">d3 = np.array([[[<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>],[<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>]],[[<span class="number">7</span>,<span class="number">8</span>,<span class="number">9</span>],[<span class="number">10</span>,<span class="number">11</span>,<span class="number">12</span>]]])</span><br><span class="line">print(d1.ndim, d2.ndim, d3.ndim)		<span class="comment"># 1 2 3</span></span><br><span class="line">print(d1.shape, d2.shape, d3.shape)		<span class="comment"># (6,) (2, 3) (2, 2, 3)</span></span><br></pre></td></tr></table></figure>
<h2 id="数组操作"><a href="#数组操作" class="headerlink" title="数组操作"></a>数组操作</h2><ol>
<li>改变数据类型：astype</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">a = np.array([<span class="number">1.7</span>, <span class="number">1.2</span>, <span class="number">1.6</span>])</span><br><span class="line">b = a.astype(int)		<span class="comment"># b = array([1, 1, 1])</span></span><br></pre></td></tr></table></figure>
<h3 id="形状操作"><a href="#形状操作" class="headerlink" title="形状操作"></a>形状操作</h3><ol>
<li><p>reshape</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line">a = np.array([<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>])</span><br><span class="line">b = a.reshape((<span class="number">2</span>,<span class="number">3</span>))</span><br><span class="line"><span class="comment"># b = array([[1, 2, 3],</span></span><br><span class="line"><span class="comment">#            [4, 5, 6]])</span></span><br><span class="line">a[<span class="number">0</span>]=<span class="number">10</span></span><br><span class="line"><span class="comment"># a = array([10,  2,  3,  4,  5,  6])</span></span><br><span class="line"><span class="comment"># b = array([[10, 2, 3],</span></span><br><span class="line"><span class="comment">#            [4, 5, 6]])</span></span><br><span class="line">b[<span class="number">0</span>][<span class="number">0</span>]=<span class="number">5</span></span><br><span class="line"><span class="comment"># a = array([5,  2,  3,  4,  5,  6])</span></span><br><span class="line"><span class="comment"># b = array([[5, 2, 3],</span></span><br><span class="line"><span class="comment">#            [4, 5, 6]])</span></span><br><span class="line">c = b.reshape((<span class="number">-1</span>,<span class="number">2</span>))</span><br><span class="line"><span class="comment"># array([[5, 2],</span></span><br><span class="line"><span class="comment">#       [3, 4],</span></span><br><span class="line"><span class="comment">#       [5, 6]])</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>shape：和reshape差不多的用法，<code>a.reshape((-1,2))</code>和<code>a.shape=(-1,2)</code>效果是一样的</p>
</li>
<li><p>resize：同上，<code>a.resize((-1,2))</code>，注意reshape和resize的参数是元组，而shape的参数则不是元组。此外，一般来说reshape有返回值，不对原始多维数组进行修改；resize无返回值，会对原始多维数组进行修改。但其实resize和reshape都可以有返回值，也都可以没有返回值，区别在于，reshape是改变形状而不改变数据量，或者说改变数组维度，如果reshape之后的元素数量和之前的不一致就会报错，但是resize不会，元素多了就去掉，少了就补零。</p>
</li>
<li><p>ravel：扁平化，多维变成一维数组，但是修改ravel之后的元素，<strong>会</strong>导致原始数组的元素跟着变。</p>
</li>
<li><p>flatten：扁平化，多维变成一维数组，修改flatten之后的元素，<strong>不会</strong>导致原始数组的元素跟着变。</p>
</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line">a = np.array([[<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>],[<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>]])</span><br><span class="line">b = a.ravel()	<span class="comment"># b = ([1,2,3,4,5,6])</span></span><br><span class="line">b[<span class="number">0</span>]=<span class="number">99</span></span><br><span class="line"><span class="comment">#a = array([[99,  2,  3],</span></span><br><span class="line"><span class="comment">#           [ 4,  5,  6]])</span></span><br><span class="line">c = a.flatten()  <span class="comment"># c = ([99,  2,  3,  4,  5,  6])</span></span><br><span class="line">c[<span class="number">1</span>]=<span class="number">98</span></span><br><span class="line"><span class="comment">#a = array([[99,  2,  3],</span></span><br><span class="line"><span class="comment">#           [ 4,  5,  6]])</span></span><br></pre></td></tr></table></figure>
<ol>
<li>转置：<code>数组.T</code></li>
</ol>
<h3 id="数组组合"><a href="#数组组合" class="headerlink" title="数组组合"></a>数组组合</h3><ol>
<li><p>hstack：水平</p>
</li>
<li><p>vstack：垂直</p>
</li>
<li><p>concatenate</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line">a = np.array([[<span class="number">0</span>,<span class="number">1</span>,<span class="number">2</span>],[<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>]])</span><br><span class="line">b = np.array([[<span class="number">0</span>,<span class="number">2</span>,<span class="number">4</span>],[<span class="number">6</span>,<span class="number">8</span>,<span class="number">10</span>]])</span><br><span class="line">c = np.hstack((a,b))</span><br><span class="line"><span class="comment"># [[ 0  1  2  0  2  4]</span></span><br><span class="line"><span class="comment">#  [ 3  4  5  6  8 10]]</span></span><br><span class="line">d = np.vstack((a,b))</span><br><span class="line"><span class="comment"># [[ 0  1  2]</span></span><br><span class="line"><span class="comment">#  [ 3  4  5]</span></span><br><span class="line"><span class="comment">#  [ 0  2  4]</span></span><br><span class="line"><span class="comment">#  [ 6  8 10]]</span></span><br><span class="line">e = np.concatenate((a,b),axis=<span class="number">1</span>)</span><br><span class="line"><span class="comment"># [[ 0  1  2  0  2  4]</span></span><br><span class="line"><span class="comment">#  [ 3  4  5  6  8 10]]</span></span><br><span class="line">f = np.concatenate((a,b),axis=<span class="number">0</span>)</span><br><span class="line"><span class="comment"># [[ 0  1  2]</span></span><br><span class="line"><span class="comment">#  [ 3  4  5]</span></span><br><span class="line"><span class="comment">#  [ 0  2  4]</span></span><br><span class="line"><span class="comment">#  [ 6  8 10]]</span></span><br></pre></td></tr></table></figure>
</li>
</ol>
<h3 id="数组分割"><a href="#数组分割" class="headerlink" title="数组分割"></a>数组分割</h3><ol>
<li>hsplit：水平</li>
<li>vsplit：垂直</li>
<li>split</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line">a = np.array([[<span class="number">0</span>,<span class="number">1</span>,<span class="number">2</span>],[<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>]])</span><br><span class="line">a1, a2, a3 = np.hsplit(a,<span class="number">3</span>)</span><br><span class="line">b1, b2 = np.vsplit(a,<span class="number">2</span>)</span><br><span class="line">c1, c2 = np.split(a, <span class="number">2</span>, axis=<span class="number">0</span>)</span><br><span class="line"><span class="comment"># a1 = [[0]</span></span><br><span class="line"><span class="comment">#       [3]]</span></span><br><span class="line"><span class="comment"># a2 = [[1]</span></span><br><span class="line"><span class="comment">#       [4]]</span></span><br><span class="line"><span class="comment"># a3 = [[2]</span></span><br><span class="line"><span class="comment">#       [5]]</span></span><br><span class="line"><span class="comment"># b1 = [[0 1 2]]</span></span><br><span class="line"><span class="comment"># b2 = [[3 4 5]]</span></span><br><span class="line"><span class="comment"># c1 = [[0 1 2]]</span></span><br><span class="line"><span class="comment"># c2 = [[3 4 5]]</span></span><br></pre></td></tr></table></figure>
<h3 id="访问数组元素"><a href="#访问数组元素" class="headerlink" title="访问数组元素"></a>访问数组元素</h3><ol>
<li><p>切片下标：和列表切片一样，修改切片后的元素会导致原始数组改变</p>
</li>
<li><p>高级下标：</p>
<ol>
<li><p>整数列表/元组作为下标</p>
</li>
<li><p>整数数组作为下标</p>
</li>
<li><p>布尔数组作为下标</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">array([<span class="number">10</span>,<span class="number">9</span>,<span class="number">8</span>,<span class="number">7</span>,<span class="number">6</span>,<span class="number">5</span>,<span class="number">4</span>,<span class="number">3</span>,<span class="number">2</span>])</span><br><span class="line"><span class="comment"># 1</span></span><br><span class="line">b = a[[<span class="number">0</span>,<span class="number">-1</span>,<span class="number">5</span>,<span class="number">7</span>]]	<span class="comment">#array([10,2,5,3])</span></span><br><span class="line"><span class="comment"># 2</span></span><br><span class="line">c = a[np.array([<span class="number">3</span>,<span class="number">3</span>,<span class="number">-3</span>,<span class="number">8</span>])]	<span class="comment">#array([7,7,4,2])</span></span><br><span class="line">d = a[np.array([[<span class="number">3</span>,<span class="number">3</span>,<span class="number">-3</span>,<span class="number">8</span>],[<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>]])]	<span class="comment">#array([[7,7,4,2],[9,8,7,6]])</span></span><br><span class="line"><span class="comment"># 3</span></span><br><span class="line">array([<span class="number">5</span>,<span class="number">4</span>,<span class="number">3</span>,<span class="number">2</span>,<span class="number">1</span>])</span><br><span class="line">b = a[np.array([<span class="literal">True</span>,<span class="literal">False</span>,<span class="literal">True</span>,<span class="literal">False</span>,<span class="literal">False</span>])]	<span class="comment">#array([5,3])</span></span><br><span class="line">a[np.array([<span class="literal">True</span>,<span class="literal">False</span>,<span class="literal">True</span>,<span class="literal">True</span>,<span class="literal">False</span>])] = <span class="number">-1</span>, <span class="number">-2</span>, <span class="number">-3</span> </span><br><span class="line"><span class="comment">#array([-1, 4, -2, -3, 1])</span></span><br><span class="line">x = np.random.rand(<span class="number">4</span>)	</span><br><span class="line"><span class="comment"># [0.75217218 0.49197318 0.0754037  0.8145583 ]</span></span><br><span class="line">x &gt; <span class="number">0.5</span></span><br><span class="line"><span class="comment"># [ True False False  True]</span></span><br><span class="line">x[x&gt;<span class="number">0.5</span>]</span><br><span class="line"><span class="comment"># [0.75217218 0.8145583 ]</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>多维数组：数组不同维数的坐标用<code>,</code>隔开，例如二维数组<code>a</code>，<code>a[0,1]</code>中，0是第一维（行），1是第二维（列），每个维度内可以用切片的方式访问，例如<code>a[0,3:5]</code>和<code>a[:,2]</code>等，也可以用列表或元组下标的方式访问。</p>
<p>下标长度小于数组维数时，剩余的轴对应的下标是<code>:</code> 。</p>
<p> 所有轴的下标形状相同时，得到的数组和下标形状相同。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 数组</span></span><br><span class="line"><span class="comment"># 0, 1, 2, 3, 4, 5</span></span><br><span class="line"><span class="comment"># 10,11,12,13,14,15</span></span><br><span class="line"><span class="comment"># 20,21,22,23,24,25</span></span><br><span class="line"><span class="comment"># 30,31,32,33,34,35</span></span><br><span class="line"><span class="comment"># 40,41,42,43,44,45</span></span><br><span class="line"><span class="comment"># 50,51,52,53,54,55</span></span><br><span class="line">a[<span class="number">0</span>, <span class="number">3</span>:<span class="number">5</span>]	<span class="comment"># 第0行第3列和第4列</span></span><br><span class="line"><span class="comment"># array([3,4])</span></span><br><span class="line">a[<span class="number">4</span>:,<span class="number">4</span>:]	<span class="comment"># 第4、5行和第4、5列</span></span><br><span class="line"><span class="comment"># array([[44,45],[54,55]])</span></span><br><span class="line">a[:,<span class="number">2</span>]		<span class="comment"># 第2列</span></span><br><span class="line"><span class="comment"># array([ 2, 12, 22, 32, 42, 52])</span></span><br><span class="line">a[<span class="number">2</span>,:]		<span class="comment"># 第2行</span></span><br><span class="line"><span class="comment"># array([20, 21, 22, 23, 24, 25])</span></span><br><span class="line">a[<span class="number">2</span>::<span class="number">2</span>, ::<span class="number">2</span>]	<span class="comment">#第2行到最后一行，步长2；所有列，步长2</span></span><br><span class="line"><span class="comment"># array([[20, 22, 24], [40, 42, 44]])</span></span><br><span class="line">a[(<span class="number">0</span>,<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>),(<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>)] <span class="comment">#坐标为(0,1)(1,2)(2,3)(3,4)(4,5)的元素</span></span><br><span class="line"><span class="comment"># array([1,12,23,34,45])</span></span><br><span class="line">a[<span class="number">3</span>:,[<span class="number">0</span>,<span class="number">2</span>,<span class="number">5</span>]]	<span class="comment">#第3行到最后一行，第0、2、5列</span></span><br><span class="line"><span class="comment"># array([[30, 32, 35], [40, 42, 45], [50, 52, 55]]) </span></span><br><span class="line">mask=np.array([<span class="number">1</span>,<span class="number">0</span>,<span class="number">1</span>,<span class="number">0</span>,<span class="number">0</span>,<span class="number">1</span>], dtype=bool)</span><br><span class="line">a[mask,<span class="number">2</span>]</span><br><span class="line"><span class="comment"># array([2,22,52])</span></span><br><span class="line">a[[<span class="number">1</span>,<span class="number">2</span>]] 	<span class="comment">#相当于a[[1,2],:] </span></span><br><span class="line"><span class="comment"># array([[10, 11, 12, 13, 14, 15], [20, 21, 22, 23, 24, 25]])</span></span><br><span class="line">x=np.array([[<span class="number">1</span>,<span class="number">2</span>],[<span class="number">3</span>,<span class="number">4</span>]])</span><br><span class="line">y=np.array([[<span class="number">1</span>,<span class="number">1</span>],[<span class="number">2</span>,<span class="number">2</span>]]) </span><br><span class="line">a[x]	<span class="comment">#从2维数组变成3维数组</span></span><br><span class="line"><span class="comment"># [[[10 11 12 13 14 15]</span></span><br><span class="line"><span class="comment">#   [20 21 22 23 24 25]]</span></span><br><span class="line"><span class="comment">#  [[30 31 32 33 34 35]</span></span><br><span class="line"><span class="comment">#   [40 41 42 43 44 45]]]</span></span><br><span class="line">a[x,y] 		<span class="comment"># x和y的元素分别作为两个维度的坐标</span></span><br><span class="line"><span class="comment"># x = 1 2</span></span><br><span class="line"><span class="comment">#     3 4</span></span><br><span class="line"><span class="comment"># y = 1 1</span></span><br><span class="line"><span class="comment">#     2 2</span></span><br><span class="line"><span class="comment">#a[x,y]=[a[1][1] a[2][1]</span></span><br><span class="line"><span class="comment">#        a[3][2] a[4][2]]</span></span><br><span class="line"><span class="comment"># = [[11 21]</span></span><br><span class="line"><span class="comment">#    [32 42]]</span></span><br></pre></td></tr></table></figure>
</li>
</ol>
</li>
</ol>
<h2 id="ufunc"><a href="#ufunc" class="headerlink" title="ufunc"></a>ufunc</h2><pre><code>  1. 对数组中每个元素进行操作的函数，不需要写for循环
     2. 常用操作：加减乘除取余乘方、比较运算、布尔运算等等
     3. 自定义ufunc： frompyfunc(func, nin, nout)
</code></pre><h3 id="其他函数操作"><a href="#其他函数操作" class="headerlink" title="其他函数操作"></a>其他函数操作</h3><ol>
<li>求和sum</li>
<li>平均值mean/average</li>
<li>方差var</li>
<li>标准差std</li>
<li>中位数median</li>
<li>最值min、max、ptp、argmin、argmax</li>
<li>排序sort、argsort</li>
<li>查找nonzero(a)、where(condition[,x,y])</li>
</ol>
<h3 id="广播（这部分短期内应该用不到，就不写了）"><a href="#广播（这部分短期内应该用不到，就不写了）" class="headerlink" title="广播（这部分短期内应该用不到，就不写了）"></a>广播（这部分短期内应该用不到，就不写了）</h3><ol>
<li>让数组shape相同的操作</li>
<li>orrid对象</li>
<li>mgrid和meshgrid函数</li>
</ol>
<h2 id="文件存取"><a href="#文件存取" class="headerlink" title="文件存取"></a>文件存取</h2><ol>
<li>这部分短期内应该也就读个图像，不看了</li>
</ol>
<h2 id="课后作业"><a href="#课后作业" class="headerlink" title="课后作业"></a>课后作业</h2><p>读入图像文件Cat.jpg，并通过numpy的数组操作对图像进行修改，得到下面一系列图像： </p>
<ol>
<li>反色图像：r、g、b为原始像素颜色，则反色后的颜色为255-r、255-g、 255-b </li>
<li>灰度图像： r、g、b为原始像素颜色，变成灰度的公式为： Gray = r<em>0.299 + g</em>0.587 + b*0.114</li>
<li>水平镜像图像：左右交换</li>
<li>垂直镜像图像：上下交换</li>
<li>行和列转置后的图像 </li>
<li>逆时针旋转90°后的图像 </li>
<li>红色/绿色/蓝色通道图像：其余两通道颜色为0, 0</li>
<li>红色通道的颜色替换成红色通道的最大值 </li>
<li>红色/绿色/蓝色通道重新组合，红色变成蓝色，绿色变成红色，蓝色变成绿色 </li>
</ol>
<h3 id="思路"><a href="#思路" class="headerlink" title="思路"></a>思路</h3><p>首先读入图像：<code>im = np.array(Image.open(&quot;cat.jpg&quot;))</code></p>
<p>其次考虑保存图像，这里写了一个函数，把数组转为图像并按指定名称保存：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">saveimg</span><span class="params">(img, index)</span>:</span></span><br><span class="line">    img = Image.fromarray(img.astype(<span class="string">'uint8'</span>))</span><br><span class="line">    img.show()</span><br><span class="line">    img.save(<span class="string">'Cat'</span> + index + <span class="string">'.jpg'</span>)</span><br><span class="line">    <span class="keyword">return</span></span><br></pre></td></tr></table></figure>
<p>接下来就是图像处理部分了，考虑到有通道分离的要求，所以先把3个通道的数据提取出来，彩色图像变成数组时，是用三维数组存储的，前两个维度表示行列对应位置的像素值，第三个维度表示颜色通道，这里的通道顺序是rgb（而如果用opencv库的话，就是gbr），也就是说，<code>im[0,0,0]、im[0,0,1]、im[0,0,1]</code>就分别表示左上角那个像素的红色、绿色和蓝色值，这三个值叠加以后的结果就是彩色图像看上去的颜色，因此分离通道后，得到的是3个二维数组，如下：</p>
<p><code>r, g, b = im[:, :, 0], im[:, :, 1], im[:, :, 2]</code></p>
<ol>
<li><p>反色：这里构造一个和<code>im</code>尺寸一致且元素都是255的新数组，用这个新数组减去<code>im</code>即可。</p>
<p><code>im2 = np.ones_like(im) * 255 - im</code></p>
</li>
<li><p>灰度：按照公式对分离出来的r、g、b三个通道进行运算即可。</p>
<p><code>im3 = r * 0.299 + g * 0.587 + b * 0.114</code></p>
</li>
<li><p>水平镜像：每一行的元素逆序</p>
<p>这里是二维数组，也就是说要逆序的是列坐标，所以是第二维逆序</p>
<p><code>im4 = im[:, ::-1]</code></p>
</li>
<li><p>垂直镜像：每一列的元素逆序</p>
<p>同上，第一维逆序</p>
<p><code>im5 = im[::-1]</code></p>
</li>
<li><p>转置：这里的图像是三维数组，所以使用transpose函数来做，简单来说就是原本的第一、二维交换顺序，也就是<code>transpose(0,1,2)—&gt;transpose(1,0,2)</code></p>
<p><code>im6 = im.transpose(1, 0, 2)</code></p>
</li>
<li><p>逆时针90度：矩阵逆时针90度的操作是左乘一个负对角线上均是1、其余都是0的方阵，也就是说，转置矩阵逆序即可</p>
<p><code>im7 = im.transpose(1, 0, 2)[::-1]</code></p>
</li>
<li><p>三通道图像：把其他通道都变成0即可，最后把3个图拼起来</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">B_im = im.copy()</span><br><span class="line">B_im[:, :, [<span class="number">0</span>, <span class="number">1</span>]] = <span class="number">0</span></span><br><span class="line">G_im = im.copy()</span><br><span class="line">G_im[:, :, [<span class="number">0</span>, <span class="number">2</span>]] = <span class="number">0</span></span><br><span class="line">R_im = im.copy()</span><br><span class="line">R_im[:, :, [<span class="number">2</span>, <span class="number">1</span>]] = <span class="number">0</span></span><br><span class="line">im8 = np.concatenate((R_im, G_im, B_im), axis=<span class="number">1</span>)</span><br></pre></td></tr></table></figure>
</li>
<li><p>红色拉满：把红色通道变成255即可</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">im9 = im.copy()</span><br><span class="line">im9[:, :, <span class="number">0</span>] = <span class="number">255</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>通道重组：这里要想明白通道怎么组合，剩下的就很好做了。红色变成蓝色，绿色变成红色，蓝色变成绿色，也就是原本是红色的数值要变成蓝色通道，绿色数值变成红色通道，蓝色数值变成绿色通道，因此通道原本的<code>(0,1,2)</code>变成现在的<code>(1,2,0)</code>。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">im10 = im.copy()</span><br><span class="line">im10 = im10[:, :, [<span class="number">1</span>, <span class="number">2</span>, <span class="number">0</span>]]</span><br></pre></td></tr></table></figure>
</li>
</ol>

      
    </div>
    
    
    

    

    

    
	
	<div>
		
		<div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>
		
	</div>
	
    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/python/" rel="tag"><i class="fa fa-tag"></i> python</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/04/22/python%E8%AF%BE%E7%A8%8B%E8%AE%B0%E5%BD%95-9/" rel="next" title="python课程记录-9">
                <i class="fa fa-chevron-left"></i> python课程记录-9
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/05/12/python%E8%AF%BE%E7%A8%8B%E8%AE%B0%E5%BD%95-11/" rel="prev" title="python课程记录-11">
                python课程记录-11 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/header.jpg"
                alt="Kun Li" />
            
              <p class="site-author-name" itemprop="name">Kun Li</p>
              <p class="site-description motion-element" itemprop="description">三月樱，六月雪，也望尘莫及</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
				<a href="/archives/">
              
                  <span class="site-state-item-count">54</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">9</span>
                  <span class="site-state-item-name">categories</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">27</span>
                  <span class="site-state-item-name">tags</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/likun1208" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="likun@mail.bnu.edu.cn" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#创建数组基本方法："><span class="nav-number">1.</span> <span class="nav-text">创建数组基本方法：</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#数组的基本属性"><span class="nav-number">2.</span> <span class="nav-text">数组的基本属性</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#数组操作"><span class="nav-number">3.</span> <span class="nav-text">数组操作</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#形状操作"><span class="nav-number">3.1.</span> <span class="nav-text">形状操作</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#数组组合"><span class="nav-number">3.2.</span> <span class="nav-text">数组组合</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#数组分割"><span class="nav-number">3.3.</span> <span class="nav-text">数组分割</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#访问数组元素"><span class="nav-number">3.4.</span> <span class="nav-text">访问数组元素</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#ufunc"><span class="nav-number">4.</span> <span class="nav-text">ufunc</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#其他函数操作"><span class="nav-number">4.1.</span> <span class="nav-text">其他函数操作</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#广播（这部分短期内应该用不到，就不写了）"><span class="nav-number">4.2.</span> <span class="nav-text">广播（这部分短期内应该用不到，就不写了）</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#文件存取"><span class="nav-number">5.</span> <span class="nav-text">文件存取</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#课后作业"><span class="nav-number">6.</span> <span class="nav-text">课后作业</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#思路"><span class="nav-number">6.1.</span> <span class="nav-text">思路</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Kun Li</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Mist</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdn.bootcss.com/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  

  

  
  <style>
    .copy-btn {
      display: inline-block;
      padding: 6px 12px;
      font-size: 13px;
      font-weight: 700;
      line-height: 20px;
      color: #333;
      white-space: nowrap;
      vertical-align: middle;
      cursor: pointer;
      background-color: #eee;
      background-image: linear-gradient(#fcfcfc, #eee);
      border: 1px solid #d5d5d5;
      border-radius: 3px;
      user-select: none;
      outline: 0;
    }

    .highlight-wrap .copy-btn {
      transition: opacity .3s ease-in-out;
      opacity: 0;
      padding: 2px 6px;
      position: absolute;
      right: 4px;
      top: 8px;
    }

    .highlight-wrap:hover .copy-btn,
    .highlight-wrap .copy-btn:focus {
      opacity: 1
    }

    .highlight-wrap {
      position: relative;
    }
  </style>
  
  <script>
    $('.highlight').each(function (i, e) {
      var $wrap = $('<div>').addClass('highlight-wrap')
      $(e).after($wrap)
      $wrap.append($('<button>').addClass('copy-btn').append('Copy').on('click', function (e) {
        var code = $(this).parent().find('.code').find('.line').map(function (i, e) {
          return $(e).text()
        }).toArray().join('\n')
        var ta = document.createElement('textarea')
        document.body.appendChild(ta)
        ta.style.position = 'absolute'
        ta.style.top = '0px'
        ta.style.left = '0px'
        ta.value = code
        ta.select()
        ta.focus()
        var result = document.execCommand('copy')
        document.body.removeChild(ta)
        
          if(result)$(this).text('Success')
          else $(this).text('Fail')
        
        $(this).blur()
      })).on('mouseleave', function (e) {
        var $b = $(this).find('.copy-btn')
        setTimeout(function () {
          $b.text('Copy')
        }, 300)
      }).append(e)
    })
  </script>

<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"model":{"jsonPath":"/live2dw/assets/z16.model.json"},"display":{"position":"left","width":175,"height":350},"mobile":{"show":false},"log":false});</script></body>
</html>
<!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/src/clicklove.js"></script>
